package com.banggood.upms.common.component;

import com.alibaba.fastjson.JSONObject;
import com.banggood.silk.web.api.exception.SkbException;
import com.banggood.upms.bean.exception.ExceptionEnum;
import com.banggood.upms.bean.vo.SystemVo;
import com.banggood.upms.common.util.SnowflakeIdWorker;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class CommonComponent {

    private Logger logger = Logger.getLogger(getClass());

    @Value("${silk.snowflake.worker-id}")
    private long worker;

    @Value("${silk.snowflake.datacenter-id}")
    private long datacenter;
    @Autowired
    private RestTemplate restTemplate;

    SnowflakeIdWorker idWorker = new SnowflakeIdWorker(worker, datacenter);

    public String generateId() {
        //ID worker主键生成策略
        return String.valueOf(idWorker.nextId());
    }

    public SystemVo requestSysPerms(String url) throws Exception {
        String response;
        try {
//            long startTime = SystemPo.currentTimeMillis();
            response = restTemplate.getForObject(url, String.class);
//            long endTime = SystemPo.currentTimeMillis();
//            long consumeTime = endTime - startTime;
//            SystemPo.out.println("======================Start time : " + startTime + ", endTime : " + endTime + ";响应时间：" + consumeTime);
        } catch (Exception e) {
            throw new SkbException(ExceptionEnum.REQUEST_SYSTEM_META_ERROR.getCode(), ExceptionEnum.REQUEST_SYSTEM_META_ERROR.getMessage());
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        String permissionListStr = jsonObject.getString("result");
        SystemVo sysVoWithPermInfo = JSONObject.parseObject(permissionListStr, SystemVo.class);
        return sysVoWithPermInfo;
    }
}
